package com.nd.typehandler;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.TypeHandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @program: project2mall
 * @description: 字符串数组和字符串的经验
 * @author: shit_code_builder
 * @create: 2021-06-05 10:40
 **/
@MappedTypes(String[].class)
@MappedJdbcTypes(JdbcType.VARCHAR)
public class StringArrayHandler implements TypeHandler<String[]> {
    ObjectMapper objectMapper = new ObjectMapper();
    @SneakyThrows
    @Override
    public void setParameter(PreparedStatement preparedStatement, int index, String[] Strings, JdbcType jdbcType) throws SQLException {
        String value = objectMapper.writeValueAsString(Strings);
        preparedStatement.setString(index,value);
    }

    @SneakyThrows
    @Override
    public String[] getResult(ResultSet resultSet, String s) throws SQLException {
        String result = resultSet.getString(s);

        return transfer(result);
    }

    @Override
    public String[] getResult(ResultSet resultSet, int i) throws SQLException {
        String string = resultSet.getString(i);
        return transfer(string);
    }

    @Override
    public String[] getResult(CallableStatement callableStatement, int i) throws SQLException {
        String string = callableStatement.getString(i);
        return transfer(string);
    }

    @SneakyThrows
    private String[] transfer(String result) {
        if (result == null || "".equals(result)) {
            return new String[0];
        }
        String[] Strings = objectMapper.readValue(result, String[].class);
        return Strings;
    }
}
